package com.hznu.googleAuthenticatorDemo.service.base;

import com.hznu.googleAuthenticatorDemo.common.GoogleAuthenticator;
import com.hznu.googleAuthenticatorDemo.common.cryptolib.CryptoApp;
import com.hznu.googleAuthenticatorDemo.common.utils.PublicUtils;
import com.hznu.googleAuthenticatorDemo.common.utils.Utils;
import com.hznu.googleAuthenticatorDemo.entity.User;
import com.hznu.googleAuthenticatorDemo.service.UserService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthVerify extends HashedCredentialsMatcher {

    @Autowired
    UserService userService;

    public boolean googleAuthVerify(Integer userid,long code)
    {
        User user = userService.selectById(userid);
        long t = System.currentTimeMillis();
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(5);
        return ga.check_code(user.getSecret(),code,t);
    }

    public boolean passwordVerify(String password,User user)
    {

        boolean match = false;

        Object subCredentials = null;
        try
        {
            subCredentials = CryptoApp.PwdTransValue(password.getBytes(),PublicUtils.hexStringToBytes(user.getSalt()));
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        byte[] accountCredentials = Utils.hexStringToBytes(user.getPassword());
        match = equals(subCredentials,accountCredentials);
        return match;
    }

}
